/*************************************************************************
	> File Name: 1.client.c
	> Author: 
	> Mail: 
	> Created Time: 2021年01月28日 星期四 20时49分13秒
 ************************************************************************/

#include "head.h"
#include "cmd.h"
int sockfd;

void logout(int signum) {
    close(sockfd);
    printf("ByeBye!\n");
    exit(0);
}

int get_name(char *path, char *name) {
    printf("get_namstart\n");
    char *ptr = strrchr(path, '/');
    if (ptr == NULL) {
        strcpy(name, path);
        return 0;
    }
    strcpy(name, ptr + 1);
    printf("get_name return\n");
    return 0;
}

int main(int argc, char **argv) {
    int port;
    char buff[512] = {0}, ip[20] = {0}, name[20];
    strcpy(name, "wangyf");
    if (argc != 3) {
        fprintf(stderr, "Usage : %s ip port\n", argv[0]);
        exit(1);
    }
    strcpy(ip, argv[1]);
    port = atoi(argv[2]);
    signal(SIGINT, logout);
    if ((sockfd = socket_connect(ip, port)) < 0) {
        perror("socket_connect");
        exit(1);
    }
    
    send(sockfd, name, strlen(name), 0);

    if (recv(sockfd, buff, sizeof(buff), 0) <= 0) {
        perror("revc");
        exit(EXIT_FAILURE);
    }
    printf("<Server> : %s\n", buff);
    while (1) {
        int flag = 0;
        char cmd[1024] = {0};
        scanf("%[^\n]s", cmd);
        getchar();
        if (!strlen(cmd)) continue;
        // s a.txt
        // r
        if (strlen(cmd) == 1 && cmd[0] == 'r') {
            flag |= RECV;
            send(sockfd, (char *)&flag, sizeof(flag), 0);
            printf("Here Recv!\n");
        } else if (cmd[0] == 's' && cmd[1] == ' ') {
            flag |= SEND;
            int ack = 0;
            char file[512] = {0}, buffer[1024] = {0}, name[512] = {0};
            strcpy(file, cmd + 2);
            send(sockfd, (char *)&flag, sizeof(flag), 0);
            printf("filename =  %s\n", file);
            FILE *fp = fopen(file, "r");
            fseek(fp, 0, SEEK_END);
            ssize_t size = ftell(fp);
            send(sockfd, (void *)&size, sizeof(size), 0);
            get_name(file, name);
            send(sockfd, (void *)&name, strlen(name), 0);
            recv(sockfd, (char *)&ack, sizeof(int), 0);
            if (ack != 1) {
                printf("Error in ACK\n"); 
                exit(1);
            }
            fseek(fp, 0, SEEK_SET);
            while (1) {
                int rsize = fread(buff, 1, 1024, fp);
                if (rsize <= 0) {
                    printf("read sucess!...\n");
                    break;
                    send(sockfd, buffer, strlen(buff), 0);
                }
            }
        
        } else {
            flag |= NORMAL;
            send(sockfd, (char *)&flag, sizeof(flag), 0);
            usleep(1000);
            send(sockfd, cmd, strlen(cmd), 0);
        }
    }

    return 0;
}

